package cn.com.zcode.user.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import cn.com.zcode.user.model.User;

public class UserUtil {
	private static Logger logger = Logger.getLogger(UserUtil.class);

	public static String getUserIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	public static User getUserFromCookie(HttpServletRequest request) {
		User user = null;
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (User.COOKIE_NAME.equals(cookie.getName())) {
					String cvalue = cookie.getValue();
					String[] arr = cvalue.split("=");
					if (arr.length >= 2) {
						String username = arr[0].trim();
						String password = arr[1].trim();
						user = new User(username, password, null);
					}
				}
			}
		}
		logger.info("Get User from cookies:"+user);
		return user;
	}

	public static void addCookieUser(HttpServletResponse response,User user) {
		int saveTime = 7;
		int seconds = saveTime * 24 * 60 * 60;
		Cookie cookie = new Cookie(User.COOKIE_NAME, user.getUsername() + "=" + user.getPasswordMD5());
		cookie.setMaxAge(seconds);
		cookie.setPath("/");
		response.addCookie(cookie);
		
		logger.info("Add cookie " + cookie);
	}
	
	public static void removeCookieUser(HttpServletResponse response){
		Cookie cookie = new Cookie(User.COOKIE_NAME, "");
		cookie.setMaxAge(0);
		cookie.setPath("/");
		response.addCookie(cookie);
		logger.info("remove cookie " + cookie);
	}
	

}
